package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.app.Dialog;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.imgedit.utils.Matrix3;
import com.stark.imgedit.view.imagezoom.ImageViewTouchBase;

import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.adapter.CutAdapter;
import flc.ast.bean.MyCutBean;
import flc.ast.databinding.ActivityPicCutBinding;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.RxUtil;

public class PicCutActivity extends BaseAc<ActivityPicCutBinding> {

    public static String imgPath = "";
    private Bitmap mImgBitmap;
    private CutAdapter cutAdapter;
    private int oldPosition = 0;
    private Dialog myTipDialog;


    @Override
    protected int onCreate() {
        return R.layout.activity_pic_cut;
    }

    @Override
    public void onBackPressed() {
        myTipDialog.show();
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);
        mDataBinding.ivPicCutBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.ivCutSave.setOnClickListener(this);
        mDataBinding.rvPicCutRatioList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        cutAdapter = new CutAdapter();
        mDataBinding.rvPicCutRatioList.setAdapter(cutAdapter);
        cutAdapter.setOnItemClickListener(this);
        //提示弹框
        tipDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()){
            case R.id.ivCutSave:
                saveImg();
                break;
            //提示弹框
            case R.id.tvDialogTipCancel://取消
                myTipDialog.dismiss();
                break;
            case R.id.tvDialogTipRight://确定
                myTipDialog.dismiss();
                finish();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        cutAdapter.getItem(oldPosition).setSelect(false);
        cutAdapter.notifyItemChanged(oldPosition);
        oldPosition = position;
        cutAdapter.getItem(position).setSelect(true);
        cutAdapter.notifyItemChanged(position);
        mDataBinding.cropImgView.setRatioCropRect(mDataBinding.imageViewTouch.getBitmapRect(),
                cutAdapter.getItem(position).getRatio());
    }

    @Override
    protected void initData() {
        //设置图片
        if (imgPath == null || TextUtils.isEmpty(imgPath)) return;
        mImgBitmap = ImageUtils.getBitmap(imgPath);
        mDataBinding.imageViewTouch.setImageBitmap(mImgBitmap);
        mDataBinding.imageViewTouch.setDisplayType(ImageViewTouchBase.DisplayType.FIT_TO_SCREEN);
        mDataBinding.imageViewTouch.setScaleEnabled(false);// 禁用缩放
        mDataBinding.imageViewTouch.post(new Runnable() {
            @Override
            public void run() {
                RectF bitmapRect = mDataBinding.imageViewTouch.getBitmapRect();
                mDataBinding.cropImgView.setCropRect(bitmapRect);
            }
        });
        //裁剪数据
        List<MyCutBean> listTailor = new ArrayList<>();
        listTailor.add(new MyCutBean(getString(R.string.img_text), R.drawable.yuanshi2, R.drawable.yuanshi1, -1f, true));
        listTailor.add(new MyCutBean("1:1", R.drawable.shape_cut1, R.drawable.shape_cut1a, 1f, false));
        listTailor.add(new MyCutBean("1:2", R.drawable.shape_cut2, R.drawable.shape_cut2a, 1f / 2f, false));
        listTailor.add(new MyCutBean("1:3", R.drawable.shape_cut3, R.drawable.shape_cut3a, 1f / 3f, false));
        listTailor.add(new MyCutBean("2:3", R.drawable.shape_cut4, R.drawable.shape_cut4a, 2f / 3f, false));
        listTailor.add(new MyCutBean("3:4", R.drawable.shape_cut5, R.drawable.shape_cut5a, 3f / 4f, false));
        cutAdapter.setList(listTailor);
    }

    //裁剪并保存图片
    private void saveImg() {
        showDialog(getString(R.string.save_ing));
        RxUtil.create(new RxUtil.Callback<String>() {
            @Override
            public void doBackground(ObservableEmitter<String> emitter) {
                RectF cropRect = mDataBinding.cropImgView.getCropRect();// 剪切区域矩形
                Matrix touchMatrix = mDataBinding.imageViewTouch.getImageViewMatrix();
                float[] data = new float[9];
                touchMatrix.getValues(data);// 底部图片变化记录矩阵原始数据
                Matrix3 cal = new Matrix3(data);// 辅助矩阵计算类
                Matrix3 inverseMatrix = cal.inverseMatrix();// 计算逆矩阵
                Matrix m = new Matrix();
                m.setValues(inverseMatrix.getValues());
                m.mapRect(cropRect);// 变化剪切矩形

                Bitmap resultBit = Bitmap.createBitmap(mImgBitmap,
                        (int) cropRect.left, (int) cropRect.top,
                        (int) cropRect.width(), (int) cropRect.height());
                //保存图片
                ImageUtils.save2Album(resultBit, Bitmap.CompressFormat.PNG);
                emitter.onNext("");
            }

            @Override
            public void accept(String path) {
                dismissDialog();
                ToastUtils.showShort(R.string.save_suc);
                startActivity(HomeActivity.class);
            }
        });
    }

    //提示弹框
    private void tipDialog() {
        myTipDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_tip, null);
        myTipDialog.setContentView(inflate);
        myTipDialog.setCancelable(true);
        Window dialogWindow = myTipDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.9);
        lp.y = 50;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView cancel = inflate.findViewById(R.id.tvDialogTipCancel);
        TextView right = inflate.findViewById(R.id.tvDialogTipRight);
        cancel.setOnClickListener(this);
        right.setOnClickListener(this);
    }

}